package com.songqintuan.common.validator;

import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import com.songqintuan.common.constant.GlobalConstants;
import com.songqintuan.common.util.MessageFactory;


public class FaxValidator implements Validator,Serializable {
	protected  boolean isEmpty(String s)
	{
		return ((s.equals(null)) || (s.length()==0));
	}
	protected boolean isCharsInBag (String s, String bag)
	{
	  int i;

	  for (i = 0; i < s.length(); i++)
	  {

	      char c = s.charAt(i);
	      if (bag.indexOf(c) == -1) return false;
	  }
	  return true;
	}
	public void validate(FacesContext context, UIComponent component, Object obj)
	throws ValidatorException {
		// TODO Auto-generated method stub
		String badChar = "><[]{}?/+=|\\'\":~!@#$%^&`";
		String fax=(String)obj;
		//Validate the user name
		FacesMessage message;
		String label = (String)component.getAttributes().get("label");
		label = (null == label)?"":label;
		if(!isEmpty(fax))
		{   
			if ( isCharsInBag( fax, badChar))
			{
				message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "input.char.bad.error.message", FacesMessage.SEVERITY_ERROR,label,badChar);
				throw new ValidatorException(message);
				
			}
			//check user length
			
			if(!isCharsInBag (fax, "0123456789-(),;+"))
			{
				message = MessageFactory.getMessage(GlobalConstants.USER_BUNDLE_NAME, "input.char.must.message", FacesMessage.SEVERITY_ERROR,label,"0123456789-(),;+");
				throw new ValidatorException(message);
			}
		}

	}

}
